package com.cby.android.base.vi

import android.app.VoiceInteractor
import android.os.Build
import android.os.Bundle
import android.view.View
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import com.cby.android.base.R
import com.cby.android.base.databinding.ActivityVoiceInteractionBinding
import com.cby.android.base.kotlin.showToast

/**
 * @description: VoiceInteractionActivity
 * <p>
 *     VI(Voice Interaction)是 Android 平台特有的语音交互 API，第三方 App 可以通过它来接入系统的语音服务。
 * </p>
 * @author: ChenBaoYang
 * @createDate: 2022/7/21 3:31 下午
 */
class VoiceInteractionActivity : AppCompatActivity() {
    private val binding by lazy { ActivityVoiceInteractionBinding.inflate(layoutInflater) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)

        binding.btnConfirm.setOnClickListener {
            val bundle = Bundle().apply {
                putString("name", "Test Voice Interaction")
            }
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                startLocalVoiceInteraction(bundle)
            }
        }
    }

    override fun onLocalVoiceInteractionStarted() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            val request = testConfirmation()
            voiceInteractor.submitRequest(request)
        }
    }


    @RequiresApi(Build.VERSION_CODES.M)
    private fun testConfirmation(): VoiceInteractor.Request {
        val prompt = VoiceInteractor.Prompt(resources.getString(R.string.vi_confirmation_prompt))

        return object : VoiceInteractor.ConfirmationRequest(prompt, null) {
            override fun onConfirmationResult(confirmed: Boolean, result: Bundle?) {
                val stringId =
                    if (confirmed) R.string.vi_confirmation_confirmed else R.string.vi_confirmation_cancelled

                showToast(getString(stringId))

                if (confirmed) {
                    binding.tvConfirm.visibility = View.INVISIBLE
                }

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    stopLocalVoiceInteraction()
                }
            }

            override fun onCancel() {
                showToast(getString(R.string.vi_confirmation_timeout))
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    stopLocalVoiceInteraction()
                }
            }
        }
    }
}